package com.ztjava.common.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.Ret;
import com.ztjava.core.Constant;
import com.ztjava.core.annotation.ControllerClass;
import com.ztjava.core.base.BaseController;
import com.ztjava.core.bean.sub.PushBean;
import com.ztjava.core.client.member.ApiClient;
import com.ztjava.ext.auth.annotation.AppMethod;
import com.ztjava.ext.auth.bean.AppSession;
import com.ztjava.plugin.event.EventKit;
import com.ztjava.plugin.event.EventTag;
import com.ztjava.plugin.event.core.RequestEvent;

@ControllerClass(path="/common/push",client=ApiClient.class)
public class PushApiController extends BaseController{
	
	@AppMethod
	public void send(){
		getResponse().addHeader("Access-Control-Allow-Origin", "*");
		String callback = getPara("callback","");
		
		
		AppSession appSession = getAttr(Constant.APPSESSION);
		String to = getPara("to");
		String code = getPara("code");
		Map<String,String[]> paramMap = getParaMap();
		Map<String,String[]> map = new HashMap<String, String[]>(paramMap);
		map.remove("to");
		map.remove("code");
		map.remove("sid");
		String[][] params = new String[map.size()][2];
		int i=0; 
		for(String key:map.keySet()){
			params[i][0] = key;
			params[i][1] = map.get(key)[0];
			i = i + 1;
		}
		PushBean pushBean = new PushBean(code, "APP", appSession.getName(),to, 0, params);
		List<Ret> list = EventKit.postRemote(EventTag.COMMON_PUSH_SYNC, 
				new RequestEvent(pushBean));
		if(list.size()>0){
			if(callback.equals("")){
				renderRet(list.get(0));
			}else {
				renderText(callback+"("+list.get(0).toJson()+")");
			}
		}else {
			if(callback.equals("")){
				renderError("没有响应信息!");
			}else {
				JSONObject jsonObject = new JSONObject();
				jsonObject.put(Constant.RESULT, Constant.ERROR);
				jsonObject.put(Constant.MESSAGE, "没有响应信息!");
				renderText(callback+"("+jsonObject.toJSONString()+")");
			}
		}
	}
}
